import 'dart:collection';

import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/model/class_entity.dart';
import 'package:FineArt/core/model/student_entity.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/home/book_content_grid_page.dart';
import 'package:FineArt/page/imageview/BookPreview.dart';
import 'package:FineArt/page/imageview/FavoriteImagePreview.dart';
import 'package:FineArt/page/imageview/FavoritorChooseFolder.dart';
import 'package:FineArt/page/imageview/RoundCheckBox.dart';
import 'package:FineArt/page/imageview/RoundCheckBoxCourse.dart';
import 'package:FineArt/page/imageview/VideoPlayer.dart';
import 'package:FineArt/page/tab/MyMaterialFolder.dart';
import 'package:FineArt/page/tab/PublicMaterialFolder.dart';
import 'package:FineArt/page/tab/component/CheckImage.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:badges/badges.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

///课堂
class CoursesPageTeacher extends StatefulWidget {
  final Function setNavibarHidden;

  CoursesPageTeacher({this.setNavibarHidden});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _CoursesPageTeacherState();
  }
}

class _CoursesPageTeacherState extends State<CoursesPageTeacher> {
  final List favorites = new List();
  final List shares = new List();
  final List share2Me = new List();
  Map<int, Favorite> selectedFavorites = new HashMap();
  Map<int, ShareByMe> selectedShares = new HashMap();
  Map<int, Share2Me> selectedShare2Me = new HashMap();
  bool showBottom = false;
  int currentPageFavorites = 1;
  int currentPageShares = 1;
  int currentPageShare2me = 1;

  int tabIndex = 1;
  int tab1Select = 0;
  int tab2Select = 0;
  int tab3Select = 0;
  List<ClassEntity> clList = new List();
  List<StudentEntity> stuList = new List();
  Map class_student_map = new Map(); //班级-学生的map

  double width;

  @override
  void initState() {
    // TODO: implement initState
    // TODO: implement build
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getClasses();
    _getMyFavorites();
  }

  void _resetAll() {
    currentPageShares = 1;
    currentPageFavorites = 1;
    currentPageShare2me = 1;
    shares.clear();
    favorites.clear();
    share2Me.clear();
    showBottom = false;
    selectedShares.clear();
    selectedFavorites.clear();
    selectedShare2Me.clear();
    tab2Select = 0;
    tab1Select = 0;
    tab3Select = 0;
  }

  void _getMyFavorites() {
    _resetAll();
    _nextPage();
  }

  void _getMyShares() {
    _resetAll();
    _nextPage2();
  }

  void _getShares2me() {
    _resetAll();
    _nextPage3();
  }

  void _nextPage() {
    ResourceApi().favoriteList(currentPageFavorites, PAGE_SIZE).then((res) {
      if (res.code == 200) {
        setState(() {
          if (res.data.list != null && res.data.list.isNotEmpty) {
            favorites.addAll(res.data.list);
            currentPageFavorites++;
            buildTestData();
            rebuildFavorites();
          }
        });
      }
    });
  }

  void _nextPage2() {
    ResourceApi().myShareList(currentPageShares, PAGE_SIZE).then((res) {
      if (res.code == 200) {
        setState(() {
          if (res.data.list != null && res.data.list.isNotEmpty) {
            shares.addAll(res.data.list);
            currentPageShares++;
            rebuildShares();
          }
        });
      }
    });
  }

  void _nextPage3() {
    ResourceApi().shareList(currentPageShares, PAGE_SIZE).then((res) {
      if (res.code == 200) {
        setState(() {
          if (res.data.list != null && res.data.list.isNotEmpty) {
            share2Me.addAll(res.data.list);
            currentPageShare2me++;
            rebuildShare2Me();
          }
        });
      }
    });
  }

  void _getClasses() {
    ClassApi().classList().then((res) {
      if (res.code == 200) {
        setState(() {
          clList.clear();
          for (Class c in res.data) {
            ClassEntity entity = new ClassEntity(c.classname, c.classid);
            clList.add(entity);
          }

          if (clList.length > 0) {
            ClassEntity entity = clList[0];
            entity.isCheck = true;
            //请求学生列表
            ClassApi().studentList(entity.id).then((res) {
              if (res.code == 200) {
                List<StudentEntity> ss = [];
                ss.add(StudentEntity("全部", 0, true));
                for (Student s in res.data) {
                  StudentEntity e = new StudentEntity(s.name, s.uid, false);
                  ss.add(e);
                }
                class_student_map[entity.id] = ss;
                setState(() {
                  stuList = ss;
                });
              }
            });
          }
        });
      }
    });
  }

  void buildTestData() {
    return;
    for (int i = 0; i < favorites.length; i++) {
      if (i < favorites.length / 3) {
        favorites[i].date = "2021-05-24";
      } else if (i < favorites.length * 2 / 3) {
        favorites[i].date = "2021-05-25";
      } else {
        favorites[i].date = "2021-05-26";
      }
    }
  }

  void rebuildFavorites() {
    String date = "";
    List tmpList = [];
    for (int i = 0; i < favorites.length; i++) {
      Favorite favorite = favorites[i];
      if (i == 0) {
        date = favorite.updatedat.substring(0, 10);
        tmpList.add(date);
        tmpList.add(favorite);
      } else {
        String tmp = favorite.updatedat.substring(0, 10);
        if (tmp == date) {
          tmpList.add(favorite);
        } else {
          tmpList.add(tmp);
          tmpList.add(favorite);
          date = tmp;
        }
      }
    }

    setState(() {
      favorites.clear();
      favorites.addAll(tmpList);
    });
  }

  void rebuildShares() {
    String date = "";
    List tmpList = [];
    for (int i = 0; i < shares.length; i++) {
      ShareByMe shareByMe = shares[i];
      if (i == 0) {
        date = shareByMe.updatedat.substring(0, 10);
        tmpList.add(date);
        tmpList.add(shareByMe);
      } else {
        String tmp = shareByMe.updatedat.substring(0, 10);
        if (tmp == date) {
          tmpList.add(shareByMe);
        } else {
          tmpList.add(tmp);
          tmpList.add(shareByMe);
          date = tmp;
        }
      }
    }

    setState(() {
      shares.clear();
      shares.addAll(tmpList);
    });
  }

  void rebuildShare2Me() {
    String date = "";
    List tmpList = [];
    for (int i = 0; i < share2Me.length; i++) {
      Share2Me shareByMe = share2Me[i];
      if (i == 0) {
        date = shareByMe.updatedat.substring(0, 10);
        tmpList.add(date);
        tmpList.add(shareByMe);
      } else {
        String tmp = shareByMe.updatedat.substring(0, 10);
        if (tmp == date) {
          tmpList.add(shareByMe);
        } else {
          tmpList.add(tmp);
          tmpList.add(shareByMe);
          date = tmp;
        }
      }
    }

    setState(() {
      share2Me.clear();
      share2Me.addAll(tmpList);
    });
  }

  @override
  Widget build(BuildContext context) {
    width = MediaQuery.of(context).size.width;
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.light,
          title: Text(
            "课堂",
            style: TextStyle(color: text_black, fontSize: setSp(18)),
          ),
          backgroundColor: Colors.white,
          automaticallyImplyLeading: false,
          centerTitle: true,
        ),
        bottomNavigationBar: _getBottom(),
        body: Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          width: SizeConfig.screenWidth,
          child: Column(
            children: [
              getHeader(),
              SizedBox(
                height: getPortraitSHeight(10),
              ),
              Row(
                children: [
                  InkWell(
                      child: Text(
                        "我的备课",
                        style: TextStyle(
                            color: tabIndex == 1
                                ? class_tab_black
                                : class_tab_gray,
                            fontSize: setSp(16)),
                      ),
                      onTap: () {
                        widget.setNavibarHidden(false);
                        setState(() {
                          tabIndex = 1;
                        });

                        _getMyFavorites();
                      }),
                  SizedBox(
                    width: getPortraitSWidth(10),
                  ),
                  VerticalDivider(
                    width: getPortraitSWidth(1),
                    color: Color(0xFFd8d8d8),
                    indent: 5,
                    endIndent: 5,
                  ),
                  SizedBox(
                    width: getPortraitSWidth(10),
                  ),
                  InkWell(
                      child: Text(
                        "我的课堂",
                        style: TextStyle(
                            color: tabIndex == 2
                                ? class_tab_black
                                : class_tab_gray,
                            fontSize: setSp(16)),
                      ),
                      onTap: () {
                        widget.setNavibarHidden(false);
                        setState(() {
                          tabIndex = 2;
                        });

                        _getMyShares();
                      }),
                  SizedBox(
                    width: getPortraitSWidth(10),
                  ),
                  VerticalDivider(
                    width: getPortraitSWidth(1),
                    color: Color(0xFFd8d8d8),
                    indent: 5,
                    endIndent: 5,
                  ),
                  SizedBox(
                    width: getPortraitSWidth(10),
                  ),
                  InkWell(
                      child: Text(
                        "学生投送",
                        style: TextStyle(
                            color: tabIndex == 3
                                ? class_tab_black
                                : class_tab_gray,
                            fontSize: setSp(16)),
                      ),
                      onTap: () {
                        widget.setNavibarHidden(false);
                        setState(() {
                          tabIndex = 3;
                        });

                        _getShares2me();
                      }),
                  // Expanded(
                  //   child: Text(""),
                  // ),
                  // Offstage(
                  //     offstage: tabIndex == 1,
                  //     child: InkWell(
                  //       onTap: () {
                  //         ToastUtils.toast("切换用户");
                  //       },
                  //       child: Image.asset(
                  //         "assets/images/icon_switch_user.png",
                  //         height: getPortraitSHeight(21.5),
                  //         width: getPortraitSWidth(20.5),
                  //       ),
                  //     )),
                ],
              ),
              SizedBox(
                height: getPortraitSHeight(10),
              ),
              Flexible(child: getFlexibleGrid())
            ],
          ),
        ));
  }

  Widget getFlexibleGrid() {
    if (tabIndex == 1)
      return _widgetTab1GroupGrid();
    else if (tabIndex == 2) {
      return _widgetTab2GroupGrid();
    } else {
      return _widgetTab3GroupGrid();
    }
  }

  void _handleDelete() {
    if (tabIndex == 1) //delete my favorite
    {
      for (Favorite f in selectedFavorites.values) {
        ResourceApi().deleteFavorite(f.id);
      }
      _getMyFavorites();
    } else // delete my shares
    {
      for (ShareByMe s in selectedShares.values) {
        ResourceApi().deleteShare(s.id);
      }
      _getMyShares();
    }
    setState(() {
      showBottom = false;
      selectedShares.clear();
      selectedFavorites.clear();
      tab2Select = 0;
      tab1Select = 0;
      widget.setNavibarHidden(false);
    });
  }

  void startShare() {
    if (clList.isEmpty || stuList.isEmpty) {
      ToastUtils.error("获取班级或学生信息错误");
      return;
    }

    int classId = -1;
    for (ClassEntity c in clList) {
      if (c.isCheck) {
        classId = c.id;
        break;
      }
    }

    if (classId == -1) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    List<String> members = [];
    for (StudentEntity s in stuList) {
      if (!s.isAll && s.isCheck) {
        members.add(s.id.toString());
      }
    }
    if (members.isEmpty) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    if (tabIndex == 1) //cast my favorite
    {
      for (Favorite f in selectedFavorites.values) {
        Favorite resource = f;

        ShareBody shareBody = new ShareBody(
            resid: resource.resid,
            type: resource.restype,
            url: resource.url,
            title: resource.title,
            uids: members);
        ResourceApi().share(shareBody);
      }
    } else // cast my shares
    {
      for (ShareByMe s in selectedShares.values) {
        ShareByMe resource = s;

        ShareBody shareBody = new ShareBody(
            resid: resource.resid,
            type: resource.restype,
            url: resource.url,
            title: resource.title,
            uids: members);
        ResourceApi().share(shareBody);
      }
    }

    setState(() {
      showBottom = false;
      selectedShares.clear();
      selectedFavorites.clear();
      tab2Select = 0;
      tab1Select = 0;
      widget.setNavibarHidden(false);
    });
  }

  void _handleCast() {
    setState(() {
      showBottom = false;
      widget.setNavibarHidden(false);
    });

    chooseStudents();
  }

  Widget _getBottom() {
    return Container(
      width: SizeConfig.screenWidth,
      height: showBottom ? getPortraitSHeight(49) : 0,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
              color: Color(0x80000000),
              offset: Offset(0.0, 0.0), //阴影y轴偏移量
              blurRadius: 0, //阴影模糊程度
              spreadRadius: 0 //阴影扩散程度
              )
        ],
      ),
      child: Row(children: [
        Expanded(child: Text("")),
        Container(
          margin: EdgeInsets.only(right: getPortraitSWidth(12.5)),
          child: Row(
            children: [
              Container(
                  width: getPortraitSWidth(110),
                  alignment: Alignment.center,
                  child: InkWell(
                      child: Text(
                        "删除",
                        style: TextStyle(
                            fontSize: setSp(18), color: Color(0xFFf11325)),
                      ),
                      onTap: () {
                        // ToastUtils.toast("删除");
                        _handleDelete();
                      }),
                  height: getPortraitSHeight(43),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(radius(21.5)),
                      bottomLeft: Radius.circular(radius(21.5)),
                    ),
                    color: Colors.white,
                    border: Border(
                        left: BorderSide(
                            color: Color(0xFFf11325),
                            width: getPortraitSWidth(1)),
                        top: BorderSide(
                            color: Color(0xFFf11325),
                            width: getPortraitSWidth(1)),
                        //此处应该不需要添加,但不添加所有的边框就不显示了不知道为什么
                        right: BorderSide(
                            color: Color(0xFFf11325),
                            width: getPortraitSWidth(1)),
                        bottom: BorderSide(
                            color: Color(0xFFf11325),
                            width: getPortraitSWidth(1))),
                  )),
              Container(
                child: InkWell(
                  child: Text("投送",
                      style:
                          TextStyle(fontSize: setSp(18), color: Colors.white)),
                  onTap: () {
                    // ToastUtils.toast("投送");
                    _handleCast();
                  },
                ),
                height: getPortraitSHeight(43),
                width: getPortraitSWidth(110),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(radius(21.5)),
                      bottomRight: Radius.circular(radius(21.5)),
                    ),
                    border: Border.all(
                        color: Color(0xFFf11325), width: getPortraitSWidth(1)),
                    color: Color(0xFFf11325)),
              ),
            ],
          ),
        ),
      ]),
    );
  }

  Widget _widget_grid() {
    double width = MediaQuery.of(context).size.width * 0.98;
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        currentPageFavorites = 1;
        favorites.clear();
        _nextPage();
      },
      onLoad: () async {
        _nextPage();
      },
      slivers: <Widget>[
        SliverPadding(
            padding: EdgeInsets.only(left: 3, right: 3),
            sliver: SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 0,
                crossAxisSpacing: 0,
                childAspectRatio: 1,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  //创建子widget
                  var resource = favorites[index];
                  if (index % 5 == 1) {
                    return _getTitleRow(index, false);
                  } else {
                    return _getImageItem(resource.url, index);
                  }
                  // return GridItemPhoto(
                  //     url: resource.url,
                  //     width: width / 3,
                  //     height: width / 3,
                  //     onTap: () {
                  //       FavoriteImagePreview.JumpToPreview(
                  //           currentPageFavorites, index, favorites, context);
                  //     });
                },
                childCount: favorites.length,
              ),
            )),

        //=====列表=====//
      ],
    );
  }

  Widget _widgetTab1GroupGrid() {
    double width = MediaQuery.of(context).size.width * 0.99;
    ScrollController _scrollController = new ScrollController();
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      // controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        _getMyFavorites();
      },
      onLoad: () async {
        _nextPage();
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 5));
            },
            child: Padding(
              padding: const EdgeInsets.only(top: 6, left: 0, right: 0),
              child: StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  crossAxisCount: 3,
                  crossAxisSpacing: getPortraitSWidth(3),
                  mainAxisSpacing: 4,
                  itemCount: favorites.length,
                  itemBuilder: (context, index) {
                    dynamic item = favorites[index];
                    if (item is Favorite) {
                      return _getImageItem(item.url, index);
                    } else if (item is String) {
                      return _getTitleRow(index, index == 0);
                    }
                  },
                  staggeredTileBuilder: (int index) {
                    dynamic item = favorites[index];
                    if (item is String) {
                      return StaggeredTile.count(3, 0.2);
                    } else {
                      return StaggeredTile.count(1, 1);
                    }
                  }),
            ),
            // (index) => new StaggeredTile.count(2, index==0?2.5:3)),
          ),
        ),
      ],
    );
  }

  Widget _widgetTab2GroupGrid() {
    double width = MediaQuery.of(context).size.width * 0.99;
    ScrollController _scrollController = new ScrollController();
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      // controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        _getMyShares();
      },
      onLoad: () async {
        _nextPage2();
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 5));
            },
            child: Padding(
              padding: const EdgeInsets.only(top: 6, left: 0, right: 0),
              child: StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  crossAxisCount: 3,
                  crossAxisSpacing: getPortraitSWidth(3),
                  mainAxisSpacing: 4,
                  itemCount: shares.length,
                  itemBuilder: (context, index) {
                    // var resource = shares[index];
                    // if (resource. rowTitle != null) {
                    //   return _getTitleRowTab2(index, index == 0);
                    // } else {
                    //   return _getImageItemTab2(resource.url, index);
                    // }

                    dynamic item = shares[index];
                    if (item is ShareByMe) {
                      return _getImageItemTab2(item.url, index);
                    } else if (item is String) {
                      return _getTitleRowTab2(index, index == 0);
                    }
                  },
                  staggeredTileBuilder: (int index) {
                    // var resource = shares[index];
                    // if (resource.rowTitle != null) {
                    //   return StaggeredTile.count(3, 0.2);
                    // } else {
                    //   return StaggeredTile.count(1, 1);
                    // }

                    dynamic item = shares[index];
                    if (item is String) {
                      return StaggeredTile.count(3, 0.2);
                    } else {
                      return StaggeredTile.count(1, 1);
                    }
                  }),
            ),
          ),
        ),
      ],
    );
  }

  Widget _widgetTab3GroupGrid() {
    double width = MediaQuery.of(context).size.width * 0.99;
    ScrollController _scrollController = new ScrollController();
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      // controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        _getShares2me();
      },
      onLoad: () async {
        _nextPage3();
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 5));
            },
            child: Padding(
              padding: const EdgeInsets.only(top: 6, left: 0, right: 0),
              child: StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  crossAxisCount: 3,
                  crossAxisSpacing: getPortraitSWidth(3),
                  mainAxisSpacing: 4,
                  itemCount: share2Me.length,
                  itemBuilder: (context, index) {
                    dynamic item = share2Me[index];
                    if (item is Share2Me) {
                      return _getImageItemTab3(item.url, index);
                    } else if (item is String) {
                      return _getTitleRowTab3(index, index == 0);
                    }
                  },
                  staggeredTileBuilder: (int index) {
                    // var resource = shares[index];
                    // if (resource.rowTitle != null) {
                    //   return StaggeredTile.count(3, 0.2);
                    // } else {
                    //   return StaggeredTile.count(1, 1);
                    // }

                    dynamic item = share2Me[index];
                    if (item is String) {
                      return StaggeredTile.count(3, 0.2);
                    } else {
                      return StaggeredTile.count(1, 1);
                    }
                  }),
            ),
          ),
        ),
      ],
    );
  }

  Widget getHeader() {
    return Row(
      children: [
        Expanded(
          child: FlatButton(
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return MyMaterialFolderPage();
              }));
            },
            color: Colors.blue,
            child: Row(
              children: [
                Image.asset(
                  "assets/images/wodedangxuan1.png",
                  width: 24,
                  height: 24,
                ),
                SizedBox(
                  width: getPortraitSWidth(8.5),
                ),
                Text(
                  "我的素材",
                  style: TextStyle(color: Colors.white, fontSize: setSp(15)),
                )
              ],
            ),
            padding: EdgeInsets.symmetric(vertical: 13.5, horizontal: 34.5),
          ),
        ),
        SizedBox(
          width: getPortraitSWidth(9.5),
        ),
        Expanded(
          child: FlatButton(
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return PublicMaterialFolderPage();
              }));
            },
            color: bg_green,
            child: Row(
              children: [
                Image.asset(
                  "assets/images/fangzihover.png",
                  width: 24,
                  height: 24,
                ),
                SizedBox(
                  width: getPortraitSWidth(8.5),
                ),
                Text(
                  "校园素材",
                  style: TextStyle(color: Colors.white, fontSize: setSp(15)),
                )
              ],
            ),
            padding: EdgeInsets.symmetric(vertical: 13.5, horizontal: 34.5),
          ),
        )
      ],
    );
  }

  Widget _getTitleRow(int index, bool isShowSelect) {
    // Favorite res = tabIndex == 1 ? favorites[index] : shares[index];

    String title = favorites[index];

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          //
          Text(
            "${title}",
            style: TextStyle(color: text_black, fontSize: setSp(14)),
          ),
          Offstage(
              offstage: !isShowSelect,
              child: InkWell(
                  onTap: () {
                    setState(() {
                      if (tab1Select == 0) {
                        tab1Select = 1;
                      } else {
                        tab1Select = 0;
                        showBottom = false;
                        widget.setNavibarHidden(false);
                        for (dynamic item in favorites) {
                          if (item is Favorite) {
                            item.isChecked = false;
                          }
                        }
                      }
                    });
                  },
                  child: Padding(
                    padding: EdgeInsets.all(0),
                    child: Text(
                      tab1Select == 1 ? "取消" : "选择",
                      style: TextStyle(color: text_black, fontSize: setSp(14)),
                    ),
                  )))
        ],
      ),
    );
  }

  Widget _getImageItem(String url, index) {
    Favorite res = favorites[index];
    return CheckImage(
        onTap: () {
          List<Favorite> fs = [];
          int idx = 0;
          for (dynamic item in favorites) {
            if (item is Favorite) {
              fs.add(item);
              if (item.id == res.id) {
                idx = fs.length - 1;
              }
            }
          }
          Favorite favorite = fs[idx];
          if (favorite.restype == 1 || favorite.restype == 5001) //image
          {
            FavoriteImagePreview.JumpToPreview(
                currentPageFavorites, idx, fs, context);
          } else if (favorite.restype == 0 || favorite.restype == 5000) //book
          {


            // FavoriteImagePreview.JumpToPreview(
            //     currentPageFavorites, idx, fs, context);

            Resource resource =
                new Resource(type: favorite.restype, id: favorite.resid,page: idx);

            jumpToBookImagePreview(favorite.url, resource,favorite.subitem);
            // BookContentListPage.JumpToBookContentList(resource, context, false);
          } else if (favorite.restype == 2 || favorite.restype == 5002) //video
          {
            Resource resource = new Resource(
                type: favorite.restype,
                id: favorite.resid,
                title: favorite.title);
            VideoPlayer.JumpToVideoView(resource, context);
          }
        },
        url: url,
        isCheck: res.isChecked,
        isShowCheck: tab1Select == 1 ? true : false,
        width: SizeConfig.screenWidth / 3,
        checkChange: (bool isCheck) {
          // ToastUtils.toast("$isCheck");
          if (isCheck) {
            selectedFavorites[index] = res;
          } else {
            selectedFavorites.remove(index);
          }
          setState(() {
            res.isChecked = isCheck;
            showBottom = selectedFavorites.length > 0;
            widget.setNavibarHidden(true);
          });
        });
  }

  void jumpToBookImagePreview(String url ,Resource resource,int subItem) {

    int pageInt = subItem;
    if (subItem == 0) {
      int index = url.lastIndexOf("/") + 1;
      String page = url.substring(index);
      LogUtil.d("book  >>   index $index  $page");
      page = page.replaceAll(".jpg", "");
      page = page.replaceAll(".png", "");
    // LogUtil.d("book  >>   tryParse ${int.tryParse(page)}");
    if (int.tryParse(page) != null) {
      pageInt = int.parse(page) - 1;
    }
    else if (resource.page != null) {
      pageInt = resource.page;
    }
  }
    BookPreview.JumpToPreview(resource, context,true,pageInt);
  }
  Widget _getTitleRowTab2(int index, bool isShowSelect) {
    // Favorite res = shares[index];
    String title = shares[index];

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          //
          Text(
            // "title-${res.rowTitle}",
            "${title}",
            style: TextStyle(color: text_black, fontSize: setSp(14)),
          ),
          Offstage(
              offstage: !isShowSelect,
              child: InkWell(
                  onTap: () {
                    // ToastUtils.toast(
                    //   tab2Select == 1 ? "取消" : "选择",
                    // );
                    setState(() {
                      if (tab2Select == 0) {
                        tab2Select = 1;
                      } else {
                        tab2Select = 0;
                        showBottom = false;
                        widget.setNavibarHidden(false);
                        for (dynamic item in shares) {
                          if (item is ShareByMe) {
                            item.isChecked = false;
                          }
                        }
                      }
                    });
                  },
                  child: Padding(
                    padding: EdgeInsets.all(0),
                    child: Text(
                      tab2Select == 1 ? "取消" : "选择",
                      style: TextStyle(color: text_black, fontSize: setSp(14)),
                    ),
                  )))
        ],
      ),
    );
  }

  Widget _getTitleRowTab3(int index, bool isShowSelect) {
    // Favorite res = shares[index];
    String title = share2Me[index];

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          //
          Text(
            // "title-${res.rowTitle}",
            "${title}",
            style: TextStyle(color: text_black, fontSize: setSp(14)),
          ),
          Offstage(
              offstage: !isShowSelect,
              child: InkWell(
                  onTap: () {
                    // ToastUtils.toast(
                    //   tab2Select == 1 ? "取消" : "选择",
                    // );
                    setState(() {
                      if (tab3Select == 0) {
                        tab3Select = 1;
                      } else {
                        tab3Select = 0;
                        showBottom = false;
                        widget.setNavibarHidden(false);
                        for (dynamic item in shares) {
                          if (item is Share2Me) {
                            item.isChecked = false;
                          }
                        }
                      }
                    });
                  },
                  child: Padding(
                    padding: EdgeInsets.all(0),
                    child: Text(
                      tab3Select == 1 ? "取消" : "选择",
                      style: TextStyle(color: text_black, fontSize: setSp(14)),
                    ),
                  )))
        ],
      ),
    );
  }

  Widget _getImageItemTab2(String url, index) {
    ShareByMe res = shares[index];
    return CheckImage(
        onTap: () {
          List<ShareByMe> fs = [];
          int idx = 0;
          for (dynamic item in shares) {
            if (item is ShareByMe) {
              fs.add(item);
              if (item.id == res.id) {
                idx = fs.length - 1;
              }
            }
          }

          ShareByMe favorite = fs[idx];
          if (favorite.restype == 0 || favorite.restype == 5000) //book
          {
            Resource resource =
                new Resource(type: favorite.restype, id: favorite.resid);
            // BookPreview.JumpToPreview(resource, context,true);
            jumpToBookImagePreview(favorite.url, resource,favorite.subitem);
            // BookContentListPage.JumpToBookContentList(resource, context, false);
          } else if (favorite.restype == 2 || favorite.restype == 5002) //video
          {
            Resource resource = new Resource(
                type: favorite.restype,
                id: favorite.resid,
                title: favorite.title);
            VideoPlayer.JumpToVideoView(resource, context);
          } else {
            FavoriteImagePreview.JumpToPreview(
                currentPageFavorites, idx, fs, context);
          }
        },
        url: url,
        isCheck: res.isChecked,
        isShowCheck: tab2Select == 1 ? true : false,
        width: SizeConfig.screenWidth / 3,
        checkChange: (bool isCheck) {
          // ToastUtils.toast("$isCheck");
          if (isCheck) {
            selectedShares[index] = res;
          } else {
            selectedShares.remove(index);
          }
          setState(() {
            res.isChecked = isCheck;
            showBottom = selectedShares.length > 0;
            widget.setNavibarHidden(true);
          });
        });
  }

  Widget _getImageItemTab3(String url, index) {
    Share2Me res = share2Me[index];
    return CheckImage(
        onTap: () {
          List<Share2Me> fs = [];
          int idx = 0;
          for (dynamic item in share2Me) {
            if (item is Share2Me) {
              fs.add(item);
              if (item.id == res.id) {
                idx = fs.length - 1;
              }
            }
          }

          Share2Me favorite = fs[idx];
          if (favorite.restype == 0 || favorite.restype == 5000) //book
          {
            Resource resource =
                new Resource(type: favorite.restype, id: favorite.resid);
            // BookPreview.JumpToPreview(resource, context,true);
            jumpToBookImagePreview(favorite.url, resource,favorite.subitem);
            // BookContentListPage.JumpToBookContentList(resource, context, false);
          } else if (favorite.restype == 2 || favorite.restype == 5002) //video
          {
            Resource resource = new Resource(
                type: favorite.restype,
                id: favorite.resid,
                title: favorite.title);
            VideoPlayer.JumpToVideoView(resource, context);
          } else {
            FavoriteImagePreview.JumpToPreview(
                currentPageShare2me, idx, fs, context);
          }
        },
        url: url,
        isCheck: res.isChecked,
        isShowCheck: tab3Select == 1 ? true : false,
        width: SizeConfig.screenWidth / 3,
        checkChange: (bool isCheck) {
          // ToastUtils.toast("$isCheck");
          if (isCheck) {
            selectedShare2Me[index] = res;
          } else {
            selectedShare2Me.remove(index);
          }
          setState(() {
            res.isChecked = isCheck;
            showBottom = selectedShare2Me.length > 0;
            widget.setNavibarHidden(true);
          });
        });
  }

  Widget buildImageItem(String url, String avatar, String info,
      BuildContext context, Function checkChange, bool isCheck) {
    bool isShowCheck = tab2Select == 1;
    Image avartImg = null;
    if (avatar == null) {
      // avartImg = Image.asset(
      //   "assets/images/icon_header_default.png",
      //   width: getPortraitSWidth(21),
      //   height: getPortraitSHeight(21),
      // );
    } else {
      avartImg = Image(
          width: getPortraitSWidth(21),
          height: getPortraitSHeight(21),
          image: CachedNetworkImageProvider(
            avatar,
          ));
    }
    Stack stack = new Stack(
      alignment: Alignment.centerLeft,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(radius(0)),
          child: InkWell(
            onTap: () {
              // ToastUtils.toast(url);
            },
            child: Image(
                width: SizeConfig.screenWidth / 3,
                height: SizeConfig.screenWidth / 3,
                image: CachedNetworkImageProvider(
                  url,
                )),
          ),
        ),
        Positioned(
            bottom: getPortraitSHeight(5),
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(
                  vertical: 2, horizontal: getPortraitSWidth(8)),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(radius(20)),
                  color: Color.fromARGB(0, 0, 0, 0)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  if (avartImg != null) avartImg,
                  SizedBox(
                    width: getPortraitSWidth(0),
                  ),
                  Text(
                    info,
                    style: TextStyle(color: Colors.white, fontSize: setSp(10)),
                  )
                ],
              ),
            )),
        Positioned(
            right: 0,
            bottom: 0,
            child: isShowCheck
                ? RoundCheckBoxCourse(
                    value: isCheck,
                    onChanged: (bool val) {
                      checkChange(val);
                    },
                  )
                : Text(""))
      ],
    );

    return stack;
  }

  /////////////////////////

  void chooseStudents() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return _buildBottomContainer(setState);
          });
        });
  }

  Widget _buildBottomContainer(Function setState) {
    return Container(
      height: 400, //对话框高度就是此高度
      child: Stack(
        children: [
          Positioned(
              bottom: 52,
              width: width,
              height: 300,
              child: Row(
                children: [
                  Expanded(
                      child: ListView.builder(
                          itemCount: clList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildClassItem(index, setState);
                          })),
                  VerticalDivider(
                    width: 2,
                    color: Colors.blueGrey,
                  ),
                  Expanded(
                      child: ListView.builder(
                          itemCount: stuList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildStuItem(index, setState);
                          })),
                ],
              )),
          Positioned(
              bottom: 50,
              width: width,
              child: Divider(
                color: Colors.grey,
                height: 1,
              )),
          Positioned(
            bottom: 0,
            height: 50,
            width: width,
            child: InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                  startShare();
                },
                child: Center(
                  child: Text("确定"),
                )),
          ),
        ],
      ),
    );
  }

  Widget _buildClassItem(int index, Function setState) {
    ClassEntity entity = clList[index];
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: entity.isCheck,
              isRadio: true,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (clList[index].isCheck) // radio效果，选中的时候再点击，
                {
                  setState(() {
                    clList[index].isCheck = true;
                  });

                  return;
                }
                if (val) {
                  setState(() {
                    for (int i = 0; i < clList.length; i++) {
                      bool check = i == index ? true : false;
                      clList[i].isCheck = check;
                    }
                  });
                } else {
                  setState(() {
                    clList[index].isCheck = val;
                  });
                }

                //如果学生列表存在
                if (class_student_map.containsKey(entity.id)) {
                  setState(() {
                    stuList = class_student_map[entity.id];
                  });
                } else {
                  //请求学生列表
                  ClassApi().studentList(entity.id).then((res) {
                    if (res.code == 200) {
                      List<StudentEntity> ss = [];
                      ss.add(StudentEntity("全部", 0, true));
                      for (Student s in res.data) {
                        StudentEntity e =
                            new StudentEntity(s.name, s.uid, false);
                        ss.add(e);
                      }
                      class_student_map[entity.id] = ss;
                      setState(() {
                        stuList = ss;
                      });
                    }
                  });
                }
              }),
          Text(entity.name)
        ]));
  }

  Widget _buildStuItem(int index, Function setState) {
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: stuList[index].isCheck,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (index == 0) {
                  for (int i = 0; i < stuList.length; i++) {
                    setState(() {
                      stuList[i].isCheck = val;
                    });
                  }
                } else {
                  setState(() {
                    stuList[index].isCheck = val;
                  });
                }
              }),
          Text(stuList[index].name)
        ]));
  }
}
